package cn.itsource.zuul1020.config;

import cn.itsource.basic.aop.LogAop;
import cn.itsource.domain.Log;
import cn.itsource.mapper.LogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

//@Aspect 开启切面
//@Component 交给spring容器管理
@Aspect
@Component
@Slf4j
public class MyLogAop {

    @Autowired
    LogMapper logMapper;


    @Pointcut("@annotation(myLog)")
    public void cut(LogAop myLog){

    }

//    在方法之前执行
    @Before("cut(Object)")
    public void before(JoinPoint joinPoint){
        //RequestContextHolder  从tomcat里面拿到 ServletRequest 拿 HttpServletRequest
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //拿到对应的url
        String url = request.getRequestURI();
        //拿到对应的ip   0.0.0.0.0.1
        String ip = request.getRemoteHost();
        String remoteAddr = request.getRemoteAddr();
        //拿到所有参数的名称
//        Enumeration<String> attributeNames = request.getAttributeNames();
//        //获取所有的参数
//        StringBuilder stringBuilder = new StringBuilder();
//
//        while (attributeNames.hasMoreElements()){
//            stringBuilder.append("参数名:")
//                    .append(attributeNames.nextElement())
//                    .append("参数值:")
//                    .append(request.getAttribute(attributeNames.nextElement()));
//        }
//        String s = stringBuilder.toString();
        Object[] argss = joinPoint.getArgs();
        String args = argss.toString();
        //获取对应的类以及方法
        Object target = joinPoint.getTarget();
        Class<?> aClass = target.getClass();
        //获取当前类
        String typeName = aClass.getTypeName();
        //获取当前方法
        String method = joinPoint.getSignature().getName();


        log.info("获取到当前的ip:{},获取到当前的url:{}",ip,url);
        //获取session
        HttpSession session = request.getSession();
        //Employee employee = (Employee) session.getAttribute(Constant.USER_SESSION);
        String userId = "0";
        //获取mapper
//        SpringUtil.getBean()
      //  if (Objects.nonNull(employee)){
       //     id = employee.getId();
       // }
        logMapper.insert(new Log(url,ip,typeName,method,args,userId,null));

    }
}